/**
 * 4. 寻找两个正序数组的中位数
 * https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
 */

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
const findMedianSortedArrays = (nums1, nums2) => {
  const length1 = nums1.length;
  const length2 = nums2.length;
  const totalLength = length1 + length2;
  const isOdd = totalLength % 2;
  const centerIndex1 = isOdd ? Math.floor(totalLength / 2) : Math.floor(totalLength / 2) - 1;
  const centerIndex2 = isOdd ? centerIndex1 : centerIndex1 + 1;
  let center1;
  let center2;
  let currentIndex = 0;
  let i1 = 0;
  let i2 = 0;
  while (i1 < length1 && i2 < length2) {
    const num1 = nums1[i1];
    const num2 = nums2[i2];
    let current;
    if (num1 <= num2) {
      current = num1;
      i1 += 1;
    } else {
      current = num2;
      i2 += 1;
    }
    if (currentIndex === centerIndex1) {
      center1 = current;
    }
    if (currentIndex === centerIndex2) {
      center2 = current;
      break;
    }
    currentIndex += 1;
  }
  if (typeof center2 === 'undefined') {
    let lefts;
    let leftsLength;
    let leftBegin;
    if (i1 < length1) {
      lefts = nums1;
      leftsLength = length1;
      leftBegin = i1;
    } else if (i2 < length2) {
      lefts = nums2;
      leftsLength = length2;
      leftBegin = i2;
    }
    if (leftBegin >= 0) {
      for (let i = leftBegin; i < leftsLength; i += 1) {
        const current = lefts[i];
        if (currentIndex === centerIndex1) {
          center1 = current;
        }
        if (currentIndex === centerIndex2) {
          center2 = current;
          break;
        }
        currentIndex += 1;
      }
    }
  }
  return (center1 + center2) / 2;
};

console.log(findMedianSortedArrays([1, 3], [2]) === 2);
console.log(findMedianSortedArrays([1, 2], [3, 4]) === 2.5);
console.log(findMedianSortedArrays([0, 0], [0, 0]) === 0);
console.log(findMedianSortedArrays([], [1]) === 1);
console.log(findMedianSortedArrays([2], []) === 2);
console.log(findMedianSortedArrays([], [2, 3]) === 2.5);
